package com.dzx.awt;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

/**
 * @author dzx
 * @ClassName:
 * @Description:
 * @date 2019年07月22日 10:00:19
 */
public class DrawDemo {
    private final String RECT_SHAPE = "rect";
    private final String OVAL_SHAPE = "oval";

    private Frame frame = new Frame("TEST");
    private Button button1 = new Button("rect");
    private Button button2 = new Button("oval");

    private MyCanvas myCanvas = new MyCanvas();
    private String Shape = "";

    public DrawDemo() {
        init();
    }

    public void init() {
        Panel p = new Panel();
        myEvent();
        p.add(button1);
        p.add(button2);
        myCanvas.setPreferredSize(new Dimension(250, 180));
        frame.add(myCanvas);
        frame.add(p, BorderLayout.SOUTH);  //设置容器p所在的位置
        frame.pack();
        frame.setSize(500, 400);
        frame.setVisible(true);
    }

    private void myEvent() {
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Shape = RECT_SHAPE;
                    myCanvas.repaint();
            }
        });
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Shape = OVAL_SHAPE;
                    myCanvas.repaint();
            }
        });
    }

    public static void main(String[] args) {
        new DrawDemo();
    }


    class MyCanvas extends Canvas {

        public void paint(Graphics g) {

            Random random = new Random();
            if (Shape.equals(RECT_SHAPE)) {  //随机
                g.setColor(new Color(200, 100, 80));
                g.drawRect(random.nextInt(200), random.nextInt(120), 40, 60);
            }
            if (Shape.equals(OVAL_SHAPE)) {
                g.setColor(new Color(200, 100, 80));
                g.drawOval(random.nextInt(200), random.nextInt(120), 50, 40);
            }

        }
    }
}


